package cn.wolfcode.business.service.impl;

import cn.wolfcode.business.domain.BusAppointment;
import cn.wolfcode.business.domain.BusStatement;
import cn.wolfcode.business.mapper.BusAppointmentMapper;
import cn.wolfcode.business.service.IBusAppointmentService;
import cn.wolfcode.business.service.IBusStatementService;
import cn.wolfcode.business.util.RegexUtils;
import cn.wolfcode.business.util.VehiclePlateNoUtil;
import cn.wolfcode.common.utils.DateUtils;
import cn.wolfcode.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 养修信息预约Service业务层处理
 * 
 * @author wolfcode
 * @date 2025-04-28
 */
@Service
public class BusAppointmentServiceImpl implements IBusAppointmentService 
{
    @Autowired
    private BusAppointmentMapper busAppointmentMapper;
    @Autowired
    private IBusStatementService busStatementService;

    /**
     * 查询养修信息预约
     * 
     * @param id 养修信息预约主键
     * @return 养修信息预约
     */
    @Override
    public BusAppointment selectBusAppointmentById(Long id)
    {
        return busAppointmentMapper.selectBusAppointmentById(id);
    }

    /**
     * 查询养修信息预约列表
     * 
     * @param busAppointment 养修信息预约
     * @return 养修信息预约
     */
    @Override
    public List<BusAppointment> selectBusAppointmentList(BusAppointment busAppointment)
    {
        return busAppointmentMapper.selectBusAppointmentList(busAppointment);
    }

    /**
     * 新增养修信息预约
     * 
     * @param busAppointment 养修信息预约
     * @return 结果
     */
    @Override
    public int insertBusAppointment(BusAppointment busAppointment)
    {
        //  1. 参数合理化验证。
        if(busAppointment == null){
            throw new RuntimeException("非法参数");
        }
        // 	2. 前台所有验证过的后台都要二次验证。（数据不能为 Null）。
        if(busAppointment.getCustomerPhone() == null || busAppointment.getAppointmentTime() == null
            || busAppointment.getLicensePlate() == null || StringUtils.isEmpty(busAppointment.getCarSeries())
            || busAppointment.getServiceType() == null){
            throw new RuntimeException("非法参数");
        }
        // 	3. 联系方式合法性验证。
        if(!RegexUtils.isPhoneLegal(busAppointment.getCustomerPhone())){
            throw new RuntimeException("手机号码格式有误");
        }
        // 	4. 车牌号码合法性验证。
        VehiclePlateNoUtil.VehiclePlateNoEnum vehiclePlateNo =
                VehiclePlateNoUtil.getVehiclePlateNo(busAppointment.getLicensePlate());
        if(vehiclePlateNo == null){
            throw new RuntimeException("车牌号码格式有误");
        }
        // 	5. 预约时间要 > 当前时间。
        Date now = DateUtils.getNowDate();
        if(!busAppointment.getAppointmentTime().after(now)){
            throw new RuntimeException("预约时间有误");
        }
        // 	6. 为了程序安全，我们需要将状态设置为 预约中。
        // 因为会通过非法参数的方式对我们进行攻击。为了安全考虑，很多公司会要求前端传入的参数禁止使用。
        // 若要求没有那么严格。我们也必须将一些关键字段（没有插入且关键字段）从新设置值。
        busAppointment.setStatus(BusAppointment.STATUS_BOOKING);
        busAppointment.setCreateTime(DateUtils.getNowDate());
        return busAppointmentMapper.insertBusAppointment(busAppointment);
    }

    /**
     * 修改养修信息预约
     * 
     * @param busAppointment 养修信息预约
     * @return 结果
     */
    @Override
    public int updateBusAppointment(BusAppointment busAppointment)
    {
        //  1. 参数合理化验证。
        if(busAppointment == null){
            throw new RuntimeException("非法参数");
        }
        // 	2. 前台所有验证过的后台都要二次验证。（数据不能为 Null）。
        if(busAppointment.getCustomerPhone() == null || busAppointment.getAppointmentTime() == null
                || busAppointment.getLicensePlate() == null || StringUtils.isEmpty(busAppointment.getCarSeries())
                || busAppointment.getServiceType() == null){
            throw new RuntimeException("非法参数");
        }
        // 必须是预约中的记录才可以进行编辑操作
        // 防止而已攻击。我们可以先从数据库中通过 id 将该对象重新查询出来。判断使用查询出来的对象的状态
        // 因为状态是不能改变的。传入的和查询出来的应该状态一致的。
        BusAppointment oldObj = this.selectBusAppointmentById(busAppointment.getId());
        if(oldObj == null){
            throw new RuntimeException("非法参数");
        }
        if(!BusAppointment.STATUS_BOOKING.equals(oldObj.getStatus())){
            throw new RuntimeException("只有状态是预约中的记录才可以进行编辑操作");
        }
        // 	3. 联系方式合法性验证。
        if(!RegexUtils.isPhoneLegal(busAppointment.getCustomerPhone())){
            throw new RuntimeException("手机号码格式有误");
        }
        // 	4. 车牌号码合法性验证。
        VehiclePlateNoUtil.VehiclePlateNoEnum vehiclePlateNo =
                VehiclePlateNoUtil.getVehiclePlateNo(busAppointment.getLicensePlate());
        if(vehiclePlateNo == null){
            throw new RuntimeException("车牌号码格式有误");
        }
        // 	5. 预约时间要 > 当前时间。
        Date now = DateUtils.getNowDate();
        if(!busAppointment.getAppointmentTime().after(now)){
            throw new RuntimeException("预约时间有误");
        }
        // 	6. 为了程序安全，我们需要将状态设置为 预约中。
        busAppointment.setStatus(BusAppointment.STATUS_BOOKING);
        return busAppointmentMapper.updateBusAppointment(busAppointment);
    }

    /**
     * 批量删除养修信息预约
     * 
     * @param ids 需要删除的养修信息预约主键
     * @return 结果
     */
    @Override
    public int deleteBusAppointmentByIds(Long[] ids)
    {
        return busAppointmentMapper.deleteBusAppointmentByIds(ids);
    }

    /**
     * 删除养修信息预约信息
     * 
     * @param id 养修信息预约主键
     * @return 结果
     */
    @Override
    public int deleteBusAppointmentById(Long id)
    {
        if(id == null){
            throw new RuntimeException("非法参数");
        }
        BusAppointment busAppointment = this.selectBusAppointmentById(id);
        if (busAppointment == null) {
            throw new RuntimeException("非法参数");
        }
        if(!BusAppointment.STATUS_BOOKING.equals(busAppointment.getStatus())){
            throw new RuntimeException("必须是预约中的用户才可以进行删除操作");
        }
        return busAppointmentMapper.deleteBusAppointmentById(id);
    }

    /**
     * 到店操作
     */
    @Override
    public int arrived(Long id) {
        // 参数合法性验证
        if (id == null) {
            throw new RuntimeException("非法参数");
        }
        // 必须是预约中的用户才可以进行到店操作
        BusAppointment busAppointment = this.selectBusAppointmentById(id);
        if(busAppointment == null){
            throw new RuntimeException("非法参数");
        }
        if(!BusAppointment.STATUS_BOOKING.equals(busAppointment.getStatus())){
            throw new RuntimeException("必须是预约中的用户才可以进行到店操作");
        }
        // 完成到店（局部更新）
        return busAppointmentMapper.changeStatusAndTimeById(BusAppointment.STATUS_ARRIVED,new Date(),id);
    }

    @Override
    public int cancel(Long id) {
        // 参数合法性验证
        if (id == null) {
            throw new RuntimeException("非法参数");
        }
        // 必须是预约中的用户才可以进行到店操作
        BusAppointment busAppointment = this.selectBusAppointmentById(id);
        if(busAppointment == null){
            throw new RuntimeException("非法参数");
        }
        if(!BusAppointment.STATUS_BOOKING.equals(busAppointment.getStatus())){
            throw new RuntimeException("必须是预约中的用户才可以进行取消操作");
        }
        return busAppointmentMapper.changeStatusById(BusAppointment.STATUS_USER_CANCELLED,id);
    }

    /**
     * 根据 ID 修改预约单状态
     * @param appointmentId
     * @param status
     */
    @Override
    public void updateStatusById(Long appointmentId, Integer status) {
        busAppointmentMapper.changeStatusById(status,appointmentId);
    }

    /**
     * 查找或生成结算单（结算单按钮）
     */
    @Override
    @Transactional
    public Long createOrSelectStatement(Long id) {
        // 合理化校验
        if (id == null) {
            throw new RuntimeException("非法参数");
        }
        BusAppointment busAppointment = this.selectBusAppointmentById(id);
        if(busAppointment == null){
            throw new RuntimeException("非法参数");
        }
        // 判断预约单状态。必须是 已到店、已结算、已支付才可以点击
        if(BusAppointment.STATUS_BOOKING.equals(busAppointment.getStatus())
            || BusAppointment.STATUS_USER_CANCELLED.equals(busAppointment.getStatus())
            || BusAppointment.STATUS_TIMEOUT_CANCELLED.equals(busAppointment.getStatus())){
            throw new RuntimeException("预约单处于预约中、用户取消、超时取消则不允许生成/查找结算单");
        }
        // 根据预约单 ID 取查询结算单
        BusStatement statement = busStatementService.selectByAppointmentId(id);
        if(statement == null){
            // 若没找到结算单则创建新的结算单
            statement = new BusStatement();
            statement.setCustomerName("客服录入");
            statement.setCustomerPhone(busAppointment.getCustomerPhone());
            statement.setActualArrivalTime(busAppointment.getActualArrivalTime());
            statement.setLicensePlate(busAppointment.getLicensePlate());
            statement.setCarSeries(busAppointment.getCarSeries());
            statement.setServiceType(busAppointment.getServiceType());
            statement.setAppointmentId(id);
            statement.setStatus(BusStatement.STATUS_CONSUME);
            statement.setInfo(busAppointment.getInfo());
            statement.setIsDelete(BusStatement.IS_NOT_DELETE);
            statement.setCreateTime(new Date());
            busStatementService.insertBusStatement(statement);
            // 将预约单状态更新为已结算。
            busAppointmentMapper.changeStatusById(BusAppointment.STATUS_SETTLED,id);
        }
        // 判断一下 is_delete 状态。
        if(BusStatement.IS_DELETE.equals(statement.getIsDelete())){
            // 说明当前记录已经被删除，我们需要恢复数据。修改 is_delete = 0
            busStatementService.changeIsDeleteStatus(statement.getId(),BusStatement.IS_NOT_DELETE);
        }
        // 若找到结算单则返回结算单 ID
        return statement.getId();
    }
}
